package com.alexatguigu.juc042202.Service;

import com.alexatguigu.juc042202.entity.MovieSeat;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class CinemaService {
    // 模拟影院座位(实际项目中会存数据库)
    private final List<MovieSeat> seats = new ArrayList<>();
    // 创建一个锁
    private final Lock lock = new ReentrantLock();
    
    // 初始化5个座位
    @PostConstruct
    public void init() {
        for(int i = 1; i <= 5; i++) {
            seats.add(new MovieSeat(i, false, null));

        }
    }
    
    // 查看所有座位
    public List<MovieSeat> getAllSeats() {
        return seats;
    }
    
    // 选座位(使用Lock方式)
    public String bookSeatWithLock(Integer seatId, String userName) {
        lock.lock();
        try {
            return getString(seatId, userName);
        } finally {
            lock.unlock();
        }
    }

    // 选座位(使用synchronized方式)
    public synchronized String bookSeatWithSync(Integer seatId, String userName) {
        // 找到对应座位
        return getString(seatId, userName);
    }

    private String getString(Integer seatId, String userName) {
        // 找到对应座位
        MovieSeat seat = seats.stream()
            .filter(s -> s.getSeatId().equals(seatId))
            .findFirst()
            .orElse(null);

        if(seat == null) {
            return "座位号不存在";
        }

        if(seat.getIsOccupied()) {
            return "座位已被" + seat.getOccupiedBy() + "占用";
        }

        // 订座
        seat.setIsOccupied(true);
        seat.setOccupiedBy(userName);
        return userName + "成功预订座位" + seatId;
    }
}